import axios from 'axios'
import { getToken } from '@/utils/auth'

// const mimeMap = {
//   xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
//   zip: 'application/zip'
// }

const baseUrl = process.env.VUE_APP_BASE_API
export function downLoadZip(str, params) {
  const url = baseUrl + str
  axios({
    method: 'get',
    url: url,
    params,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + getToken() }
  }).then(res => {
    // let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    // const url = URL.createObjectURL(blob)
    // const url = window.URL.createObjectURL(new Blob([res.data]));
    const a = document.createElement('a')
    // let fileName=data.headers["content-disposition"].split(";")[1].split("=")[1];  //filename名称截取
    // fileName = decodeURI(fileName);
    a.style = 'display: none'
    a.href = `${url}?start_time=${params?.start_time}&end_time=${params?.end_time}&token=${getToken()}`
    // a.download = "报备审核"; //命名下载名称
    a.click() // 点击触发下载
    window.URL.revokeObjectURL(url) // 下载完成进行释放
    document.body.removeChild(a)
    // resolveBlob(res, mimeMap.zip)
  })
}

export function downLoadFile(str) {
  var url = baseUrl + str
  const aLink = document.createElement('a')
  aLink.href = url
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}
/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res, mimeType) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition'])
  var result = patt.exec(contentDisposition)
  var fileName = result[1]
  fileName = fileName.replace(/\"/g, '')
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}
